<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/08/18
 */
namespace api\modules\mp\models;

use common\tool\Curd;
use yii\base\Model;
use yii\web\NotFoundHttpException;

class Cabin extends Model {
    use Curd;

    public static function tableName() {
        return 'mp_cabin';
    }
    public function rules() {
        return [
            [['title','personNum','price'],'required'],
            [['price','personNum'],'number','min'=>1],
        ];
    }
    public function attributeLabels() {
        return [
            'title'=>'房间名',
            'personNum'=>'人数',
            'price'=>'价格',
        ];
    }

    public static function build($data = []): ?self {
        if (!empty($data['id'])) {
            $one = self::getOne("id={$data['id']}");
            if (!$one) throw new NotFoundHttpException();
            $data = array_merge($one, $data);
        }
        return new self($data);
    }

    public $id;
    public $title;
    public $boatId;
    public $personNum = 0;
    public $enrollNum = 0;
    public $price = 0;
    public $ctime;
    public $utime;

    public function save() {
        $data = [
            'title' => $this->title,
            'boat_id' => $this->boatId,
            'person_num' => $this->personNum,
            'price' => $this->price,
        ];
        $now = date('Y-m-d H:i:s');
        if ($this->id) {
            $data['utime'] = $now;
            self::update($data, 'id=:id', [':id' => $this->id]);
        } else {
            $data['ctime'] = $data['utime'] = $now;
            $id = self::insert($data);
            $this->id = $id;
        }
    }

    public function info() {
        return $this->getAttributes();
    }
}
